package com.framework.spring.web;

import com.framework.spring.annotations.Autowired;
import com.framework.spring.annotations.Component;
import com.framework.spring.annotations.PostConstruct;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import java.io.File;

@Component
public class TomcatServer {

    @Autowired
    private DispatcherServlet dispatcherServlet;

    @PostConstruct
    public void init() throws LifecycleException {
        // 1. 创建 Tomcat 实例
        Tomcat tomcat = new Tomcat();

        // 2. 配置端口和基础目录
        tomcat.setPort(8080);
        tomcat.getConnector();

        // 3. 创建 Web 应用的上下文（等同于部署 WAR）
        String contextPath = "";
        String docBase = new File("").getAbsolutePath();
        Context context = tomcat.addWebapp(contextPath, docBase);

        tomcat.addServlet(contextPath, "dispatcherServlet", dispatcherServlet);
        context.addServletMappingDecoded("/*", "dispatcherServlet");

        // 5. 启动 Tomcat
        tomcat.start();
        System.out.println("Tomcat started on port 8080. Access URL: http://localhost:8080");
    }

}
